﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fuse8.ContentManagementFramework.Administration.Models;
using Fuse8.ContentManagementFramework.BizFacade;
using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.ContentManagementFramework.Administration.Controllers
{
    public class CmsSearchController : CmsAdminController
    {

        public ActionResult SearchSnippet()
        {
            return PartialView("SearchSnippet", new CmsAdminSearchSnippetModel());
        }

        [HttpPost]
        public ActionResult Search(CmsAdminSearchSnippetModel model)
        {
            ActionResult result = null;
            if (model == null) RedirectToAction("Index", "CmsAdminHome");

            if (ModelState.IsValid && model != null && !string.IsNullOrWhiteSpace(model.SearchQuery))
            {
                var searchResults = new CmsAdminSearchModel() { SearchQuery = model.SearchQuery.Trim() };
                
                searchResults.Results = SearchInAreas(searchResults.SearchQuery, model.SearchAreas.Where(e => e != CmsAdminSearchSnippetModel.AllAreasItem));

                result = View(searchResults);
            }

            return result ?? RedirectToAction("Index", "CmsAdminHome");
        }

        [NonAction]
        public static IEnumerable<CmsAdminSearchResult> SearchInAreas(string searchQuery, IEnumerable<string> areas)
        {
            Guard.ArgumentNotNull(searchQuery, "searchQuery");
            Guard.ArgumentNotNull(areas, "areas");

            var results = new List<CmsAdminSearchResult>();

            foreach (var searchArea in areas)
            {
                var service = DependencyServiceLocator.Current.GetInstance<ICmsSearchService>(searchArea);

                var areaResults = service.Search(searchQuery);

                foreach (var result in areaResults)
                {
                    result.SearchArea = searchArea;
                    results.Add(result);
                }

            }

            return results;
        }
    }
}
